package com.wzx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wzx.mapper.AdminMapper;
import com.wzx.mapper.RoleMapper;
import com.wzx.mapper.SysRoleMapper;
import com.wzx.mapper.UserMapper;
import com.wzx.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class AdminDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,username);
        Admin admin = adminMapper.selectOne(queryWrapper);

        if (Objects.isNull(admin)){
            throw new RuntimeException("用户名和密码错误!");
        }
        LoginAdmin loginAdmin = new LoginAdmin();
        loginAdmin.setAdmin(admin);
        //TODO 查询对应的权限
        List<String> list = new ArrayList<>();
        List<SysRole> sysRoles = sysRoleMapper.selectList(new LambdaQueryWrapper<SysRole>().eq(SysRole::getSysId, admin.getId()));
        for (SysRole sysRole : sysRoles) {
            list.add(roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRoleId, sysRole.getRoleId())).getRoleKey());
        }

//        log.info("list:{}",list);
//        List<String> list = menuMapper.selectPermsByUserId(user.getUserId());
        loginAdmin.setPermissions(list);
        return loginAdmin;
    }
}
